package site.xuxingcan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private static String TOKEN = null;
    private static Gson gson = new Gson();
    private static String USER_NAME = "13665436269";
    private static String USER_PWD = "111";
    private static ArrayList<String> Order2Confirm = new ArrayList<>();

    static {
        Order2Confirm.add("xwwl1701020105");
//        Order2Confirm.add("xwwl1612250496");
//        Order2Confirm.add("xwwl1612250497");
//        Order2Confirm.add("xwwl1612240256");
    }

    private static long startTime;

    public static void main(String[] args) {
        // write your code here
        validate(USER_NAME, USER_PWD);
        String orderListJson = getOrderList();
        System.out.println(orderListJson);
        ArrayList<OrderModel> list = gson.fromJson(orderListJson,
                new TypeToken<List<OrderModel>>() {
                }.getType());
        for (final OrderModel orderModel : list) {
            if (Order2Confirm.contains(orderModel.getShipmentCode())) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(orderModel.getZbShipmentId() + " TenderInterval = " + orderModel.getTenderInterval());
                        try {
                            Thread.sleep(orderModel.getTenderInterval() - 2 * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        startTime = System.currentTimeMillis();
                        System.out.println(orderModel.getZbShipmentId() + " startTime = " + startTime);
                        orderConfirm(orderModel.getZbShipmentId() + "");
                    }
                }).start();
            }
        }
//        orderConfirm();
    }

    public static boolean validate(String user, String password) {
        if ((user == "") || (password == "")) {
            return false;
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://223.99.167.71:8081/xwtms/login.app");
        httpPost.addHeader("userId", user);
        httpPost.addHeader("password", password);
        httpPost.addHeader("token", "");
        httpPost.addHeader("versionCode", "11");
        httpPost.addHeader("versionName", "2.0");
        httpPost.addHeader("imei", "359788041140226");
        httpPost.addHeader("auto", "false");
        httpPost.addHeader("Connection", "keep-alive");

        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("userId", user));
        nvps.add(new BasicNameValuePair("password", password));
        nvps.add(new BasicNameValuePair("versionCode", "11"));
        nvps.add(new BasicNameValuePair("imei", "359788041140226"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        CloseableHttpResponse response2 = null;
        try {
            response2 = httpclient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result = "";
        try {
            HttpEntity entity2 = response2.getEntity();

            BufferedReader in = new BufferedReader(new InputStreamReader(entity2
                    .getContent()));
            String line;
            while ((line = in.readLine()) != null) {
                result = result + line;
            }
            System.out.print(URLDecoder.decode(result, "UTF-8"));
            result = URLDecoder.decode(result, "UTF-8");
            try {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String type = jsonObject.getString("type");
                JSONObject jsonObjectMessage = JSON.parseObject(jsonObject.getString("message"));
                String token = jsonObjectMessage.getString("token");
                TOKEN = token;
            } catch (JSONException e) {
                e.printStackTrace();
                EntityUtils.consume(entity2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    public static String getOrderList() {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost("http://223.99.167.71:8081/xwtms/remote.app");
        httpPost.addHeader("userId", USER_NAME);
        httpPost.addHeader("token", TOKEN);
        httpPost.addHeader("method", "getOrderTenderListByPager");
        httpPost.addHeader("pageSize", "100");
        httpPost.addHeader("currentSize", "0");
        httpPost.addHeader("Connection", "keep-alive");

        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("userId", USER_NAME));
        nvps.add(new BasicNameValuePair("token", TOKEN));
        nvps.add(new BasicNameValuePair("method", "getOrderTenderListByPager"));
        nvps.add(new BasicNameValuePair("pageSize", "50"));
        nvps.add(new BasicNameValuePair("currentSize", "0"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        CloseableHttpResponse response2 = null;
        try {
            response2 = httpclient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result = "";
        try {
            HttpEntity entity2 = response2.getEntity();

            BufferedReader in = new BufferedReader(new InputStreamReader(entity2
                    .getContent()));
            String line;
            while ((line = in.readLine()) != null) {
                result = result + line;
            }

            result = URLDecoder.decode(result, "UTF-8");
            try {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String type = jsonObject.getString("type");
                String tempStr = jsonObject.getString("message").replaceAll("(\n)", "");

                JSONArray jsonArrayMessage = JSON.parseArray(tempStr);
                String jsonStringMessage = jsonObject.getString("message");

                return jsonStringMessage;
            } catch (JSONException e) {
                e.printStackTrace();

                EntityUtils.consume(entity2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void orderConfirm(String zbShipmentId) {
        HttpPost httpPost = new HttpPost("http://223.99.167.71:8081/xwtms/remote.app");
        httpPost.addHeader("userId", USER_NAME);
        httpPost.addHeader("token", TOKEN);
        httpPost.addHeader("method", "orderTenderConfirm");
        httpPost.addHeader("lisence", "null");
        httpPost.addHeader("zbShipmentId", zbShipmentId);
        httpPost.addHeader("beChecked", "true");
        httpPost.addHeader("Connection", "keep-alive");

        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("userId", USER_NAME));
        nvps.add(new BasicNameValuePair("token", TOKEN));
        nvps.add(new BasicNameValuePair("method", "orderTenderConfirm"));
        nvps.add(new BasicNameValuePair("lisence", "null"));
        nvps.add(new BasicNameValuePair("zbShipmentId", zbShipmentId));
        nvps.add(new BasicNameValuePair("beChecked", "true"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(4000);
        cm.setDefaultMaxPerRoute(2000);
        HttpHost remotehost = new HttpHost("223.99.167.71", 8081);
        cm.setMaxPerRoute(new HttpRoute(remotehost), 2000);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();
        int length = 100000;

        PostRunnable[] threads = new PostRunnable[length];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new PostRunnable(httpClient, httpPost);
        }

        for (int j = 0; j < threads.length; j++) {
            threads[j].start();
        }

        for (int j = 0; j < threads.length; j++) {
            try {
                threads[j].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(zbShipmentId + " DONE spend Time = " + (System.currentTimeMillis() - startTime));
    }
}
